<template>
    <div>
        <div class="scroll-container" ref="scrollContainer" @wheel.prevent="handleScroll">
            <div class="scroll-wrapper" ref="scrollWrapper" :style="{left: left + 'px'}">
                <slot></slot>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
    const padding = 15

    import {Component, Vue} from "vue-property-decorator";

    @Component
    export default class ScrollPane extends Vue {
        private left: number = 0;

        private handleScroll(e: any) {
            const eventDelta = e.wheelDelta || -e.deltaY * 3//wheelDelta:-120;deltaY:-120
            const $container: any = this.$refs.scrollContainer//外面的container
            const $containerWidth = $container.offsetWidth//外面的container的宽度
            const $wrapper: any = this.$refs.scrollWrapper//里面
            const $wrapperWidth = $wrapper.offsetWidth//里面的宽度

            if (eventDelta > 0) {
                this.left = Math.min(0, this.left + eventDelta)//min() 方法可返回指定的数字中带有最低值的数字。
            } else {
                if ($containerWidth - padding < $wrapperWidth) {
                    if (this.left < -($wrapperWidth - $containerWidth + padding)) {
                        this.left = this.left
                    } else {
                        this.left = Math.max(this.left + eventDelta, $containerWidth - $wrapperWidth - padding)
                    }
                } else {
                    this.left = 0
                }
            }
        }
        private moveToTarget($target: any) {
            const $container: any = this.$refs.scrollContainer
            const $containerWidth = $container.offsetWidth
            const $targetLeft = $target.offsetLeft
            const $targetWidth = $target.offsetWidth

            if ($targetLeft < -this.left) {
                // tag in the left
                this.left = -$targetLeft + padding
            } else if ($targetLeft + padding > -this.left && $targetLeft + $targetWidth < -this.left + $containerWidth - padding) {
                // tag in the current view
                // eslint-disable-line
            } else {
                // tag in the right
                this.left = -($targetLeft - ($containerWidth - $targetWidth) + padding)
            }
        }
    }
</script>

<style lang="scss">
    .scroll-container {
        white-space: nowrap;
        position: relative;
        width: 100%;
        height: 40px;
        .scroll-wrapper {
            position: absolute;
            left: 0px;
            overflow-y: hidden;
            overflow-x: auto;
        }
    }
</style>
